<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="品牌名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入品牌名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="newly">新增品牌</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="text item">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        max-height="600"
      >
        <el-table-column
          type="index"
          align="center"
          :index="indexMethod"
          label="序号"
          width="60"
        >
        </el-table-column>
        <el-table-column prop="name" align="center" label="品牌名称">
        </el-table-column>
        <el-table-column prop="logo" align="center" label="品牌图片">
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.logo"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="utime" align="center" label="创建时间">
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="上架"
              inactive-text="下架"
              :active-value="1"
              :inactive-value="2"
              @change="switchCage(scope.index, scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" align="center" label="操作" width="190">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="consent(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="refuse(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 200, 300, 400]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-form ref="ruleForm" :rules="rules" :model="form" label-width="80px">
          <el-form-item prop="name" label="品牌名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="品牌图片" prop="imageUrl">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFiles"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
                :on-change="fileChange"
              >
                <el-image
                  v-if="form.imageUrl"
                  class="imageGood"
                  :src="form.imageUrl"
                  style="width: 360px; height: 180px"
                ></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="品牌状态" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="上架"
              inactive-text="下架"
              :active-value="1"
              :inactive-value="2"
              @change="switchChange()"
            >
            </el-switch>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">返 回</el-button>
        <el-button type="primary" @click="addition">保 存</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  uploadFiles,
  brandList,
  addBrand,
  setBrand,
  deleteBrand,
} from "../../../../utils/api";
import { compressImage } from "../../../../assets/js/compressImage";
export default {
  data() {
    return {
      dialogVisible: false,
      token: sessionStorage.getItem("token"),
      loading: false,
      type: 2,
      formInline: {
        name: "",
      },
      //展示数据
      tableData: [
        {
          logoItem: "",
          logo: "",
          name: "",
          status: "",
        },
      ],
      // 收集数据
      form: {
        id: "",
        name: "",
        imageUrl: "",
        imageUrl1: "",
        status: "",
      },
      imgHeader: this.Global.imgHeader,

      //上传
      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      srcList2: {},
      //校验
      rules: {
        name: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
        imageUrl: [
          { required: true, message: "请上传品牌图片", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择是否上下架", trigger: "blur" },
        ],
      },
      page: 1,
      limit: 10,
      total: 0,
    };
  },
  methods: {
    //清空添加
    empty() {
      this.form.name = "";
      this.form.imageUrl = "";
      this.form.imageUrl1 = "";
      this.form.marketable = "";
      this.form.status = "";
    },
    //查询
    onSubmit() {
      this.page = 1;
      this.BrandList();
    },
    //新增品牌
    newly() {
      this.dialogVisible = true;
    },
    //关闭弹窗
    handleClose(done) {
      done();
      this.empty();
    },
    //取消
    cancel() {
      this.dialogVisible = false;
      this.empty();
    },
    //编辑
    consent(row) {
      if (row.status == 1) {
        this.$message.warning("上架时不能编辑");
        return;
      }
      let obj = JSON.parse(JSON.stringify(row));
      this.form.id = obj.id;
      this.form.imageUrl = obj.logo;
      this.form.imageUrl1 = obj.logoItem;
      this.form.name = obj.name;
      this.form.status = obj.status;
      this.dialogVisible = true;
    },
    //删除
    refuse(row) {
      if (row.status == 1) {
        this.$message.warning("上架时不能删除");
        return;
      }
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteBrand(this.token, row.id, this.type).then((res) => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.BrandList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClosedelete(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //上传文件的格式
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 压缩文件
    compressFile() {
      let config = {
        quality: 0.5, //默认0.5  0-1
        // width:100,
        // height:100
      };
      this.fileList.forEach(async (item) => {
        // console.log("this.fileList1", this.fileList1);
        console.log("原图size1===>", item.size);
        let result = await compressImage({
          file: item.raw,
          config,
          fileName: item.name,
        });
        console.log("压缩后图片size1===>", result.finalFile.size);
        // this.imageList.push(result);
        this.srcList2 = result.finalFile;
        // console.log("aaa", result.finalFile);
        // console.log("bbb", this.srcList2);
        // console.log("this.srcList", this.srcList);
      });
      // console.log("压缩后图片1===>", this.imageList);
    },
    //上传文件的事件
    uploadFiles(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      this.compressFile();
      let timer = setTimeout(() => {
        uploadFiles(this.srcList2).then((res) => {
          if (res.data.status != false || res.data.id != null) {
            res.data.data.saveurl; //半截
            res.data.data.weburl; //全拼
            this.form.imageUrl1 = res.data.data.saveurl;
            this.form.imageUrl = res.data.data.weburl;
            this.fileList.push(this.srcList2); //成功过后手动将文件添加到展示列表里
            let i = this.fileList.indexOf(this.srcList2);
            this.handleSuccess();
          }
        });
        clearTimeout(timer);
      }, 1000);
      // uploadFiles(item.file).then((res) => {
      //   if (res.data.status != false || res.data.id != null) {
      //     console.log(res);
      //     res.data.data.saveurl; //半截
      //     res.data.data.weburl; //全拼
      //     this.form.imageUrl1 = res.data.data.saveurl;
      //     this.form.imageUrl = res.data.data.weburl;
      //     this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
      //     let i = this.fileList.indexOf(item.file);
      //     this.handleSuccess();
      //   }
      // });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClosedelete();
    },
    //序号
    indexMethod(index) {
      if (this.token < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.page - 1) * this.limit - index;
      }
    },
    //上下架
    switchChange() {},
    switchCage(index, row) {
      let obj = JSON.parse(JSON.stringify(row));
      console.log(obj);
      if (obj.status == 1) {
        this.conceal(
          this.token,
          obj.name,
          obj.logoItem,
          "",
          obj.id,
          this.type,
          1
        );
      } else {
        this.show(
          this.token,
          obj.name,
          obj.logoItem,
          obj.sort,
          obj.id,
          this.type,
          2
        );
      }
    },
    //添加品牌
    addition() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.setBrands();
          } else {
            this.addBrands();
          }
        }
      });
    },
    //分页器
    handleSizeChange(val) {
      this.limit = val;
      this.BrandList();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.BrandList();
    },
    //品牌列表
    BrandList() {
      this.loading = true;
      brandList(
        this.token,
        this.page,
        this.limit,
        this.formInline.name,
        this.type
      ).then((res) => {
        if (res.data.status) {
          this.tableData = res.data.data.data;
          this.total = res.data.data.count;
          this.tableData.forEach((item) => {
            if (item.logo) {
              item.logoItem = item.logo;
              item.logo = this.imgHeader + item.logo;
            }
          });
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          this.loading = false;
          this.$message.error(res.data.msg);
        }
      });
    },
    //添加品牌
    addBrands() {
      addBrand(
        this.token,
        this.form.name,
        this.form.imageUrl1,
        "",
        this.type,
        this.form.status
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.$refs.ruleForm.resetFields();
          this.BrandList();
        } else {
          this.$message.error(res.data.msg);
          this.BrandList();
        }
      });
    },
    //编辑
    setBrands() {
      setBrand(
        this.token,
        this.form.name,
        this.form.imageUrl1,
        "",
        this.form.id,
        this.type,
        this.form.status
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "修改成功",
            type: "success",
            onClose: (res) => {},
          });

          this.dialogVisible = false;
          this.$refs.ruleForm.resetFields();
          this.empty();
          this.BrandList();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //上架
    show(token, name, imageUrl1, sort, id, type, status) {
      setBrand(token, name, imageUrl1, sort, id, type, status).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "修改成功",
            type: "success",
            onClose: (res) => {},
          });
          this.BrandList();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 下架
    conceal(token, name, imageUrl1, sort, id, type, status) {
      setBrand(token, name, imageUrl1, sort, id, type, status).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "修改成功",
            type: "success",
            onClose: (res) => {},
          });
          this.BrandList();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
  },
  mounted() {
    this.BrandList();
  },
};
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
</style>